package com.ruoyi.web.controller.system;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.StbCompany;
import com.ruoyi.system.domain.StbEmployee;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.service.IStbCompanyService;
import com.ruoyi.system.service.IStbEmployeeService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
/**
 * 企业Controller
 * 
 * @author ruoyi
 * @date 2020-02-08
 */
@Controller
@RequestMapping("/system/company")
public class StbCompanyController extends BaseController
{
    private String prefix = "system/company";

    @Autowired
    private IStbCompanyService stbCompanyService;
    
    @Autowired
    private ISysDictDataService dictDataService;
    
    @Autowired
    private IStbEmployeeService stbEmployeeService;
    
    @Autowired
    private ISysConfigService configService;

    @RequiresPermissions("system:company:view")
    @GetMapping()
    public String company()
    {
        return prefix + "/company";
    }
    
    /*
	 * 查询新入驻企业 compname:企业名称 settlingtime:入驻时间
	 */
    @PostMapping("/newcompany")
    @ResponseBody
    public List<Map<String,Object>> selectNewCompany(){
    	StbCompany stbCompany = new StbCompany();
    	Date d=new Date(); 	
		String limitValue = configService.selectConfigByKey("company.limitdays");
		if(limitValue!=null&&!"".equals(limitValue)) {
			long limitDays = Long.valueOf(limitValue);
			Map<String,Object> params=new HashMap<>();
			SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
			String endDay=df.format(new Date(d.getTime()-limitDays* 24 * 60 * 60 * 1000));
    		params.put("afterTime", endDay);
    		stbCompany.setParams(params);
		}
    	List<Map<String, Object>> newcompList = stbCompanyService.selectNewCompany(stbCompany);
    	return newcompList;
    }
    
    /*
	 * 查询明星企业 compname:企业名称 companytabs:标签
	 */
    @PostMapping("/starcompany")
    @ResponseBody
    public List<Map<String,Object>> selectStarCompany(){
    	SysDictData dictData=new SysDictData();
    	dictData.setDictType("company_tabs");
    	List<SysDictData> dictList = dictDataService.selectDictDataList(dictData);
    	List<Map<String, Object>> resultMapList = new LinkedList<Map<String,Object>>();
    	List<StbCompany> compList = stbCompanyService.selectStbCompanyList(new StbCompany());
    	List<StbEmployee> employeeList = stbEmployeeService.selectStbEmployeeList(new StbEmployee());
    	
    	List<StbCompany> newCompList = compList.stream()
    			.filter(t->{
    				if(t.getCompanyTabs()!=null&&!t.getCompanyTabs().equalsIgnoreCase("")) {
    					String[] tabIdArr = t.getCompanyTabs().split(",");
    					List<String> tabIdList = Arrays.asList(tabIdArr);
    					List<StbEmployee> newEmpList = employeeList.stream().filter(emp->emp.getCompId()==t.getCompId()&&emp.getEmpTabs()!=null&&!emp.getEmpTabs().equalsIgnoreCase(""))
    													.collect(Collectors.toList());
    					if(tabIdList.contains("1")||tabIdList.contains("2")||tabIdList.contains("3")||newEmpList.size()>0) {
    						List<String> nameList=new ArrayList<>();
    						for (StbEmployee currentEmp : newEmpList) {
    							nameList.add(currentEmp.getEmpName());
    							if(com.ruoyi.common.utils.StringUtils.isNotEmpty(tabIdList)) {
    								tabIdList=new ArrayList<String>(tabIdList);
    							}
    							//11 高层次人才  12高学历人才
    							String empTabIdStr = currentEmp.getEmpTabs();
    							if(StringUtils.isNotEmpty(empTabIdStr)) {
    								String[] empTabArr = empTabIdStr.split(",");
    								List<String> empTabList = Arrays.asList(empTabArr);
    								if(empTabList.contains("1")||empTabList.contains("2")||empTabList.contains("3")) {
    									tabIdList.add("11");
    								}
    								if(empTabList.contains("4")||empTabList.contains("5")) {
    									tabIdList.add("12");
    								}
    								t.setCompanyTabs(StringUtils.join(tabIdList.toArray(),","));
    							}
							}
    						t.setEmpNames(StringUtils.join(nameList,","));
    						return true;
    					}
    				}
    				
    				return false;
    			})
    			.collect(Collectors.toList());
    	
    	for (StbCompany currentComp : newCompList) {
    		Map<String,Object> map = new HashMap<String,Object>();
    		map.put("compname", currentComp.getCompName());
    		String companyTabIds = currentComp.getCompanyTabs();
    		//1,2
    		String[] idArr = companyTabIds.split(",");
			List<String> idList = Arrays.asList(idArr);
    		List<SysDictData> dictCollect = dictList.stream()
	 			.filter(t->{
	 				return idList.contains(t.getDictValue());
	 			})
	 			.collect(Collectors.toList());
    		
    		List<String> tabNameList=new ArrayList<>();
    		
    		for (SysDictData sysDictData : dictCollect) {
				String dictLabel = sysDictData.getDictLabel();
				String dictValue = sysDictData.getDictValue();
				if(dictValue.equals("1")||dictValue.equals("2")||dictValue.equals("3")) {
					tabNameList.add(dictLabel);
				}				
			}
    		//11 高层次人才  12高学历人才
    		if(idList.contains("11")) {
    			tabNameList.add("高层次人才");
    		}
    		if(idList.contains("12")) {
    			tabNameList.add("高学历人才");
    		}
    		
    		Object [] tabNameArr = tabNameList.toArray();
    		String  companytabs = StringUtils.join(tabNameArr, ",");
    		
    		map.put("companytabs", companytabs);
    		map.put("empnames", currentComp.getEmpNames());
    		resultMapList.add(map);
		}
	return resultMapList;
}
    
    /*
	 * 查询各类标签企业数量  name:名称 num:数量
	 */
    @PostMapping("/tabcount")
    @ResponseBody
    public List<Map<String,Object>> selectTabTypeCount(){
    	SysDictData dictData=new SysDictData();
    	dictData.setDictType("company_tabs");
    	List<SysDictData> list = dictDataService.selectDictDataList(dictData);
    	Collections.sort(list,(x,y)->{
    		return x.getDictSort().compareTo(y.getDictSort());
    	});
    	List<Map<String, Object>> resultMapList = new LinkedList<Map<String,Object>>();
    	StbCompany stbCompany = new StbCompany();
    	List<StbCompany> compList = stbCompanyService.selectStbCompanyList(stbCompany);
    	for (SysDictData sysDictData : list) {
    		Map<String,Object> map=new HashMap<String,Object>();
			map.put("name", sysDictData.getDictLabel());
			Integer num=0;
			String key=sysDictData.getDictValue();
			for (StbCompany item : compList) {
				String companyTabs = item.getCompanyTabs();
				if(companyTabs!=null&&!companyTabs.equals("")) {
					String[] keyArr = companyTabs.split(",");
					List<String> keyList= new ArrayList<>(Arrays.asList(keyArr));
					if(keyList.contains(key)) {
						num++;
					}
				}
			}
			map.put("num",num);
			resultMapList.add(map);
		}
    	return resultMapList;
    }
    
	/*
	 * 查询各类企业数量  name:名称 num:数量
	 */
    @PostMapping("/typecount")
    @ResponseBody
    public List<Map<String,Object>> selectCompTypeCount(){
    	SysDictData dictData=new SysDictData();
    	dictData.setDictType("company_type");
    	List<SysDictData> list = dictDataService.selectDictDataList(dictData);
    	Collections.sort(list,(x,y)->{
    		return x.getDictSort().compareTo(y.getDictSort());
    	});
    	List<Map<String, Object>> maplist = new LinkedList<Map<String,Object>>();
    	StbCompany stbCompany = new StbCompany();
    	List<Map<String, Object>> compTypeList = stbCompanyService.selectCompTypeCount(stbCompany);
    	for (SysDictData sysDictData : list) {
			Map<String,Object> map=new HashMap<String,Object>();
			map.put("name", sysDictData.getDictLabel());
			Long num=0l;
			String dictValue=sysDictData.getDictValue();
			List<Map<String, Object>> collect = compTypeList.stream()
				.filter((Map<String, Object> item) -> dictValue.equals((String)item.get("company_type")))
				.collect(Collectors.toList());
			for (Map<String, Object> map2 : collect) {
				num=(Long)map2.get("num");
			}
			map.put("num", num);
			maplist.add(map);
		}
    	return maplist;
    }
	    
    /**
     * 查询企业列表
     */
    @RequiresPermissions("system:company:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StbCompany stbCompany)
    {
        startPage();
        List<StbCompany> list = stbCompanyService.selectStbCompanyList(stbCompany);
        return getDataTable(list);
    }

    /**
     * 导出企业列表
     */
    @RequiresPermissions("system:company:export")
    @Log(title = "企业", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StbCompany stbCompany)
    {
        List<StbCompany> list = stbCompanyService.selectStbCompanyList(stbCompany);
        ExcelUtil<StbCompany> util = new ExcelUtil<StbCompany>(StbCompany.class);
        return util.exportExcel(list, "company");
    }

    /**
     * 新增企业
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存企业
     */
    @RequiresPermissions("system:company:add")
    @Log(title = "企业", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StbCompany stbCompany)
    {
    	StbCompany obj= new StbCompany();
    	obj.setCompName(stbCompany.getCompName());
    	List<StbCompany> compList= stbCompanyService.selectStbCompanyList(obj);
    	if(compList!=null&&compList.size()>0) {
    		AjaxResult json = new AjaxResult();
	        json.put("msg", "企业名称已存在");
	        json.put("code", 500);
	        return json;
    	}
    	stbCompany.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(stbCompanyService.insertStbCompany(stbCompany));
    }

    /**
     * 修改企业
     */
    @GetMapping("/edit/{compId}")
    public String edit(@PathVariable("compId") Long compId, ModelMap mmap)
    {
        StbCompany stbCompany = stbCompanyService.selectStbCompanyById(compId);      
        mmap.put("stbCompany", stbCompany);
        String [] tabIds = stbCompany.getCompanyTabs()==null?new String [0]:stbCompany.getCompanyTabs().split(",");
        stbCompany.setTabIds(tabIds);
        return prefix + "/edit";
    }

    /**
     * 修改保存企业
     */
    @SuppressWarnings("null")
	@RequiresPermissions("system:company:edit")
    @Log(title = "企业", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StbCompany stbCompany)
    {
    	stbCompany.setCompanyTabs(StringUtils.join(stbCompany.getTabIds(),","));
    	StbCompany obj= new StbCompany();
    	obj.setCompName(stbCompany.getCompName());
    	List<StbCompany> compList= stbCompanyService.selectStbCompanyList(obj);
    	stbCompany.setUpdateBy(ShiroUtils.getLoginName());
    	int flag=0;//0 修改失败 1修改成功 2名称已被使用
    	if(compList==null&&compList.size()==0) {
    		flag=1;
    	}else if(compList.size()==1){
    		StbCompany stbCompany2 = compList.get(0);
    		if(stbCompany2.getCompId().equals(stbCompany.getCompId())) {
    			flag=1;
    		}else {
    			flag=2;
    		}
    	}
    	AjaxResult json = new AjaxResult();
    	if(flag==1) {
    		return toAjax(stbCompanyService.updateStbCompany(stbCompany));
    	}else if(flag==2){
	        json.put("msg", "名称已存在");
    	}else {
	        json.put("msg", "修改失败");
    	}
    	json.put("code", 500);
        return json;
    }

    /**
     * 删除企业
     */
    @RequiresPermissions("system:company:remove")
    @Log(title = "企业", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(stbCompanyService.deleteStbCompanyByIds(ids));
    }
}
